package ext.tianma.util;

import java.util.Collection;

import wt.query.ClassAttribute;
import wt.query.QueryException;
import wt.query.QuerySpec;
import wt.query.SQLFunction;
import wt.query.SearchCondition;
import wt.query.SubSelectExpression;
import wt.query.TableColumn;
import wt.util.WTPropertyVetoException;

/**
 * 类名: TMUtil </br>
 * 包名: ext.tianma.util
 * 描述: 一些常用的API
 * @author xucr
 * 创建时间: 2020年6月28日
 * 发布版本: V1.0
 */
public class TMPartUtil {
	/**
	 * 最新大版本
	 * @param parentQS 上层QuerySpec
	 * @param clazz 指定的对象 WTDocument.class or WTPart.class
	 * @param conditions 在过滤最新大版本时添加额外的（clazz）条件，例如：设计视图（或者某个制造视图)或者其它对象上的属性
	 * @return 
	 * @author xucr
	 * @CreateDate 2020年8月4日
	 */
	public static QuerySpec addSearchConditionLasterVersion(QuerySpec parentQS, Class clazz,
			Collection<SearchCondition> conditions) {
		try {
			int index = parentQS.getFromClause().getPosition(clazz); // 主查询位置
			parentQS.setAdvancedQueryEnabled(true);
			String alias = parentQS.getFromClause().getAliasAt(index);// 主查询别名
			QuerySpec subQuery = new QuerySpec();
			subQuery.getFromClause().setAliasPrefix("B");
			int index2 = subQuery.appendClassList(clazz, false);
			String alias2 = subQuery.getFromClause().getAliasAt(index2);
			TableColumn masterid = new TableColumn(alias, "Ida3masterreference");
			TableColumn masterid2 = new TableColumn(alias2, "Ida3masterreference");
			SearchCondition where1 = new SearchCondition(masterid, SearchCondition.EQUAL, masterid2);
			if (subQuery.getConditionCount() > 0) {
				subQuery.appendAnd();
			}
			subQuery.appendWhere(where1, new int[] { index, index2 });

			// conditions 添加额外的查询条件
			if (conditions != null && conditions.size() > 0) {
				for (SearchCondition condition : conditions) {
					if (subQuery.getConditionCount() > 0) {
						subQuery.appendAnd();
					}
					subQuery.appendWhere(condition, new int[] { index2 });
				}
			}
			TableColumn versionColumn = new TableColumn(alias2, "versionSortIdA2versionInfo");
			SQLFunction sf0 = SQLFunction.newSQLFunction(SQLFunction.MAXIMUM);
			sf0.setArgumentAt(versionColumn, 0);
			sf0.setColumnAlias("versionSortIdA2versionInfo");
			subQuery.appendSelect(sf0, false);
			SubSelectExpression sse = new SubSelectExpression(subQuery);
			ClassAttribute mca = new ClassAttribute(clazz, "versionInfo.identifier.versionSortId");// versionSortIdA2versionInfo
			SearchCondition sc = new SearchCondition(mca, SearchCondition.IN, sse);
			if (parentQS.getConditionCount() > 0) {
				parentQS.appendAnd();
			}
			parentQS.appendWhere(sc, new int[] { index });
		} catch (QueryException e) {
			e.printStackTrace();
		} catch (WTPropertyVetoException e) {
			e.printStackTrace();
		}
		return parentQS;
	}
}
